<template>
  <div class="basic-layout">
    <el-container>
      <!-- 侧边栏 -->
      <el-aside :width="sidebarWidth" class="sidebar-container">
        <div class="logo-container">
          <img src="@/assets/images/logo.png" alt="Logo" class="logo" v-if="!appStore.sidebarCollapsed" />
          <img src="@/assets/images/logo-mini.png" alt="Logo" class="logo-mini" v-else />
          <h1 v-if="!appStore.sidebarCollapsed" class="title">苒兴教育</h1>
        </div>
        
        <el-scrollbar class="sidebar-scrollbar">
          <el-menu
            :default-active="activeMenu"
            :collapse="appStore.sidebarCollapsed"
            :unique-opened="true"
            router
            class="sidebar-menu"
          >
            <template v-for="route in menuRoutes" :key="route.name">
              <el-menu-item
                v-if="!route.children || route.children.length === 0"
                :index="route.path"
                @click="handleMenuClick(route)"
              >
                <el-icon><component :is="route.meta.icon" /></el-icon>
                <template #title>{{ route.meta.title }}</template>
              </el-menu-item>
              
              <el-sub-menu v-else :index="route.path">
                <template #title>
                  <el-icon><component :is="route.meta.icon" /></el-icon>
                  <span>{{ route.meta.title }}</span>
                </template>
                <el-menu-item
                  v-for="child in route.children"
                  :key="child.name"
                  :index="child.path"
                  @click="handleMenuClick(child)"
                >
                  {{ child.meta.title }}
                </el-menu-item>
              </el-sub-menu>
            </template>
          </el-menu>
        </el-scrollbar>
      </el-aside>
      
      <!-- 主内容区 -->
      <el-container>
        <!-- 顶部导航栏 -->
        <el-header class="header-container">
          <div class="header-left">
            <el-button
              type="text"
              @click="appStore.toggleSidebar"
              class="sidebar-toggle"
            >
              <el-icon><Expand v-if="appStore.sidebarCollapsed" /><Fold v-else /></el-icon>
            </el-button>
            
            <!-- 面包屑导航 -->
            <el-breadcrumb separator="/" class="breadcrumb">
              <el-breadcrumb-item
                v-for="item in appStore.breadcrumbs"
                :key="item.path"
                :to="item.path"
              >
                {{ item.title }}
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          
          <div class="header-right">
            <!-- 主题切换 -->
            <el-button
              type="text"
              @click="appStore.toggleTheme"
              class="theme-toggle"
            >
              <el-icon><Sunny v-if="appStore.isDark" /><Moon v-else /></el-icon>
            </el-button>
            
            <!-- 全屏切换 -->
            <el-button
              type="text"
              @click="toggleFullscreen"
              class="fullscreen-toggle"
            >
              <el-icon><FullScreen /></el-icon>
            </el-button>
            
            <!-- 用户菜单 -->
            <el-dropdown @command="handleUserCommand" class="user-dropdown">
              <div class="user-info">
                <el-avatar :size="32" :src="userStore.userInfo?.avatar">
                  <el-icon><User /></el-icon>
                </el-avatar>
                <span class="username">{{ userStore.userName }}</span>
                <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">
                    <el-icon><User /></el-icon>
                    个人中心
                  </el-dropdown-item>
                  <el-dropdown-item command="settings">
                    <el-icon><Setting /></el-icon>
                    系统设置
                  </el-dropdown-item>
                  <el-dropdown-item divided command="logout">
                    <el-icon><SwitchButton /></el-icon>
                    退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        
        <!-- 标签页 -->
        <div class="tabs-container" v-if="appStore.tabs.length > 1">
          <el-tabs
            v-model="appStore.activeTab"
            type="card"
            @tab-click="handleTabClick"
            @tab-remove="handleTabRemove"
            class="page-tabs"
          >
            <el-tab-pane
              v-for="tab in appStore.tabs"
              :key="tab.name"
              :label="tab.title"
              :name="tab.name"
              :closable="tab.closable"
            />
          </el-tabs>
          
          <el-dropdown @command="handleTabCommand" class="tab-dropdown">
            <el-button type="text" size="small">
              <el-icon><MoreFilled /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="closeOthers">关闭其他</el-dropdown-item>
                <el-dropdown-item command="closeAll">关闭所有</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        
        <!-- 主内容 -->
        <el-main class="main-container">
          <router-view v-slot="{ Component }">
            <transition name="fade-transform" mode="out-in">
              <component :is="Component" />
            </transition>
          </router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAppStore } from '@/store/app'
import { useUserStore } from '@/store/user'
import { ElMessageBox } from 'element-plus'

const route = useRoute()
const router = useRouter()
const appStore = useAppStore()
const userStore = useUserStore()

// 计算属性
const sidebarWidth = computed(() => {
  return appStore.sidebarCollapsed ? '64px' : '240px'
})

const activeMenu = computed(() => {
  return route.path
})

const menuRoutes = computed(() => {
  return router.getRoutes()
    .filter(route => {
      return route.path === '/' && route.children
    })[0]?.children
    .filter(child => !child.meta?.hidden)
    .sort((a, b) => (a.meta?.order || 0) - (b.meta?.order || 0))
})

// 监听路由变化，更新面包屑和标签页
watch(
  () => route.path,
  () => {
    updateBreadcrumbs()
    updateTabs()
  },
  { immediate: true }
)

// 更新面包屑
const updateBreadcrumbs = () => {
  const matched = route.matched.filter(item => item.meta && item.meta.title)
  const breadcrumbs = matched.map(item => ({
    title: item.meta.title,
    path: item.path
  }))
  appStore.setBreadcrumbs(breadcrumbs)
}

// 更新标签页
const updateTabs = () => {
  if (route.meta?.title) {
    appStore.addTab({
      name: route.name,
      title: route.meta.title,
      path: route.path
    })
  }
}

// 处理菜单点击
const handleMenuClick = (menuRoute) => {
  if (menuRoute.path !== route.path) {
    router.push(menuRoute.path)
  }
}

// 处理用户菜单命令
const handleUserCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 处理退出登录
const handleLogout = () => {
  ElMessageBox.confirm(
    '确定要退出登录吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    userStore.logoutAction().then(() => {
      router.push('/login')
    })
  })
}

// 处理标签页点击
const handleTabClick = (tab) => {
  const targetTab = appStore.tabs.find(t => t.name === tab.props.name)
  if (targetTab && targetTab.path !== route.path) {
    router.push(targetTab.path)
  }
}

// 处理标签页移除
const handleTabRemove = (tabName) => {
  const targetTab = appStore.tabs.find(t => t.name === tabName)
  if (targetTab) {
    appStore.removeTab(tabName)
    if (appStore.activeTab === tabName) {
      const activeTab = appStore.tabs.find(t => t.name === appStore.activeTab)
      if (activeTab) {
        router.push(activeTab.path)
      }
    }
  }
}

// 处理标签页命令
const handleTabCommand = (command) => {
  switch (command) {
    case 'closeOthers':
      appStore.closeOtherTabs(appStore.activeTab)
      break
    case 'closeAll':
      appStore.closeAllTabs()
      const activeTab = appStore.tabs.find(t => t.name === appStore.activeTab)
      if (activeTab) {
        router.push(activeTab.path)
      }
      break
  }
}

// 切换全屏
const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen()
  } else {
    document.exitFullscreen()
  }
}
</script>

<style lang="scss" scoped>
.basic-layout {
  height: 100vh;
  
  .el-container {
    height: 100%;
  }
}

.sidebar-container {
  background: var(--el-bg-color);
  border-right: 1px solid var(--el-border-color-light);
  transition: width 0.3s;
  
  .logo-container {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 60px;
    padding: 0 16px;
    border-bottom: 1px solid var(--el-border-color-light);
    
    .logo, .logo-mini {
      height: 32px;
      width: auto;
    }
    
    .title {
      margin-left: 12px;
      font-size: 18px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
  }
  
  .sidebar-scrollbar {
    height: calc(100% - 60px);
  }
  
  .sidebar-menu {
    border-right: none;
  }
}

.header-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-light);
  
  .header-left {
    display: flex;
    align-items: center;
    
    .sidebar-toggle {
      margin-right: 16px;
      font-size: 18px;
    }
    
    .breadcrumb {
      font-size: 14px;
    }
  }
  
  .header-right {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .theme-toggle,
    .fullscreen-toggle {
      font-size: 18px;
    }
    
    .user-dropdown {
      .user-info {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px;
        cursor: pointer;
        border-radius: 4px;
        transition: background-color 0.3s;
        
        &:hover {
          background: var(--el-fill-color-light);
        }
        
        .username {
          font-size: 14px;
          color: var(--el-text-color-primary);
        }
        
        .dropdown-icon {
          font-size: 12px;
          color: var(--el-text-color-secondary);
        }
      }
    }
  }
}

.tabs-container {
  display: flex;
  align-items: center;
  padding: 0 16px;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-light);
  
  .page-tabs {
    flex: 1;
    
    :deep(.el-tabs__header) {
      margin: 0;
      border-bottom: none;
    }
    
    :deep(.el-tabs__nav) {
      border: none;
    }
    
    :deep(.el-tabs__item) {
      border: 1px solid var(--el-border-color-light);
      margin-right: 4px;
      
      &.is-active {
        background: var(--el-color-primary);
        color: white;
        border-color: var(--el-color-primary);
      }
    }
  }
  
  .tab-dropdown {
    margin-left: 8px;
  }
}

.main-container {
  background: var(--el-bg-color-page);
  overflow: auto;
}

// 页面切换动画
.fade-transform-enter-active,
.fade-transform-leave-active {
  transition: all 0.3s;
}

.fade-transform-enter-from {
  opacity: 0;
  transform: translateX(30px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}
</style>